package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.TravelForm;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.ITravelFormService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("travelForms")
public class TravelFormController {
    @Autowired
    private ITravelFormService travelFormService;

    /**
     * 新增旅行单的资源控制器
     * @param travelForm
     * @return
     */
    @PostMapping()
    public JSONResult save(TravelForm travelForm){
        JSONResult result = new JSONResult();
        User user = UserContext.getCurrentUser();
        if (user != null){
            travelForm.setUser(user);
            travelFormService.save(travelForm);
        }else {
            result.mark("你需要登录过后才能,添加旅行单哦");
        }
        return result;
    }
    @GetMapping
    public JSONResult get(TravelForm travelForm){
        JSONResult result = new JSONResult();
        User user = UserContext.getCurrentUser();
        if (user != null){
            travelForm.setUser(user);
            try {
                travelFormService.select(travelForm);
            } catch (Exception e) {
                e.printStackTrace();
                result.mark(e.getMessage());
            }
        }
        return result;
    }
    //删除旅行单的资源控制器
    @DeleteMapping
    public JSONResult delete(TravelForm travelForm){
        User user = UserContext.getCurrentUser();
        JSONResult result = new JSONResult();
        if (user != null) {
            travelForm.setUser(user);
            travelFormService.delete(travelForm);
        }
        return new JSONResult();
    }
    //根据userId 获取到所有的旅行单
    @GetMapping("/{userId}")
    public List<TravelForm> listTravelForm (@PathVariable Long userId){

        return travelFormService.listAll(userId);
    }
}
